package cn.com.zcode.core.control;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.zcode.core.service.BaseService;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BaseActionSupport<S extends BaseService> extends ActionSupport {
	private static final long serialVersionUID = 1L;

	protected S service;

	public BaseActionSupport() {
		super();

	}

	public S getService() {
		return service;
	}

	public void setService(S service) {
		this.service = service;
	}

	public void addAttribute(String key, Object value) {
		ActionContext context = ActionContext.getContext();
		context.put(key, value);
	}

	public void addSessionAttribute(String key, Object value) {
		ActionContext context = ActionContext.getContext();
		context.getSession().put(key, value);
	}

	@SuppressWarnings("unchecked")
	public <T> T getSessionAttribute(String key, Class<T> t) {
		ActionContext context = ActionContext.getContext();
		return (T) context.getSession().get(key);
	}
	@SuppressWarnings("unchecked")
	public <T> T getAttribute(String key, Class<T> t) {
		ActionContext context = ActionContext.getContext();
		return (T) context.get(key);
	}

	public Object getBean(String beaname) {
		ServletContext context = ServletActionContext.getServletContext();
		WebApplicationContext webcontext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		return webcontext.getBean(beaname);
	}

	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public void addCookie(Cookie cookie) {
		this.getResponse().addCookie(cookie);
	}

	public Cookie[] getCookies() {
		return this.getRequest().getCookies();
	}
}
